package controllers;

import java.util.List;

import models.User;
import play.data.validation.Valid;
import play.i18n.Messages;
import play.libs.Crypto;
import play.mvc.*;

@With(Secure.class)
public class Users extends Controller {

    public static User user;

    @Before
    static void setConnectedUser() {
        if (Security.isConnected()) {
            user = User.find("byUsername", Security.connected()).first();
            renderArgs.put("user", user);


        }
    }

    public static void list() {
        List<User> entities = models.User.all().fetch();
        render(entities);
    }

    public static void create(User entity) {
        render(entity);
    }

    public static void show(Long id) {
        User entity = User.findById(id);
        render(entity);
    }

    public static void edit(Long id) {
        User entity = User.findById(id);
        render(entity);
    }

    public static void delete(Long id) {
        User entity = User.findById(id);

        entity.delete();
        flash.success(Messages.get("Users.deleted"));
        Users.list();
    }

    public static void profil(Long id) {
        if (user.id == id) {
            User entity = User.findById(id);
            render(entity);


        } else {
            renderTemplate("errors/forbiden.html");
        }

    }

    public static void save(@Valid User entity) {

        entity.password = Crypto.encryptAES(entity.password);
        if (validation.hasErrors()) {
            flash.error(Messages.get("validation"));
            entity.password = null;
            render("@create", entity);
        }
        User verif = User.find("byEmail", entity.email).first();
        if (verif != null) {
            flash.error(Messages.get("Users.exist"));
            entity.password = null;
            render("@create", entity);

        } else {
            entity.save();
            flash.success(Messages.get("Users.created"));
            Admin.index();
        }
    }

    public static void update(@Valid User entity) {
        if (validation.hasErrors()) {
            flash.error(Messages.get("validation"));
            render("@edit", entity);
        }

        entity = entity.merge();


        entity.save();
        flash.success(Messages.get("Users.updated"));
        Admin.index();
    }

    public static void update_password(@Valid User entity) {

        if (validation.hasErrors()) {
            flash.error(Messages.get("validation"));
            render("@edit", entity);
        }

        entity = entity.merge();
        entity.save();
        flash.success(Messages.get("Updated.Users.Password"));
        Admin.index();
    }
}
